package com.tywj.panda.customer.common.http

import com.tywj.lib.core.common.extension.applyScheduler
import com.tywj.lib.core.common.util.JsonUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.lifecycle.extension.attachToLifecycle
import com.tywj.lib.net.retrofit.request.BaseRequest
import io.reactivex.Observable
import org.json.JSONObject

/**
 * <pre>
 *     author : June Yang
 *     time   : 2018/11/24
 *     desc   : 微信登录相关 :网络请求回调，返回数据为实体类
 *     version: 1.0
 * </pre>
 */
abstract class PDWXTokenObjectCallback<T>(private val clazz: Class<T>, isHandleErrorSelf: Boolean = false) :
    PDBaseCallback(isHandleErrorSelf) {


    //成功后微信直接返回data
    override fun onSuccess(data: String) {
        val responseData = JSONObject(data)

        val disposable = Observable.just(responseData)
            .map { JsonUtil.parseObject(data, clazz)!! }
            .applyScheduler()
            .subscribe(
                {
                    success(it)
                },
                {
                    LogUtil.printStackTrace(it)
                    onError(BaseRequest.ERROR_DATA, "")
                })
        request.lifecycleOwner?.let { disposable.attachToLifecycle(it) }

    }

    abstract fun success(data: T)
}